package controllers

import (
	"fmt"
	"simple-crm/models"
	"simple-crm/utils"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type CustomerController struct {
	DB *gorm.DB
}

type CustomerRequest struct {
	Name    string `json:"name" binding:"required"`
	Phone   string `json:"phone" binding:"required"`
	Wechat  string `json:"wechat"`
	Address string `json:"address"`
	Age     int    `json:"age"`
	Gender  string `json:"gender"`
	City    string `json:"city" binding:"required"`
	Subject string `json:"subject" binding:"required"`
	Grade   string `json:"grade"`
	Notes   string `json:"notes"`
	Status  string `json:"status" gorm:"type:enum('interested','enrolled','invalid');default:'interested'"`
}

type CustomerQuery struct {
	Page    int    `form:"page,default=1"`
	Size    int    `form:"size,default=10"`
	Search  string `form:"search"`
	Name    string `form:"name"`
	Phone   string `form:"phone"`
	Wechat  string `form:"wechat"`
	Address string `form:"address"`
	City    string `form:"city"`
	Subject string `form:"subject"`
	Status  string `form:"status,omitempty,oneof=interested contacted signed_up enrolled invalid"` // 新增状态字段
	Pushed  int    `form:"pushed"` // 新增已推送字段
}

// NewCustomerController 创建客户控制器
func NewCustomerController(db *gorm.DB) *CustomerController {
	return &CustomerController{DB: db}
}

// GetCustomers 获取客户列表
func (cc *CustomerController) GetCustomers(c *gin.Context) {
	var query CustomerQuery
	if err := c.ShouldBindQuery(&query); err != nil {
		utils.ValidationError(c, err)
		return
	}

	// 构建查询
	db := cc.DB.Model(&models.Customer{}).Preload("Creator")

	// 添加过滤条件
	// 通用搜索：搜索姓名、手机号、微信和地址
	if query.Search != "" {
		db = db.Where("name LIKE ? OR phone LIKE ? OR wechat LIKE ? OR address LIKE ?", "%"+query.Search+"%", "%"+query.Search+"%", "%"+query.Search+"%", "%"+query.Search+"%")
	}

	// 具体字段搜索
	if query.Name != "" {
		db = db.Where("name LIKE ?", "%"+query.Name+"%")
	}
	if query.Phone != "" {
		db = db.Where("phone LIKE ?", "%"+query.Phone+"%")
	}
	if query.Wechat != "" {
		db = db.Where("wechat LIKE ?", "%"+query.Wechat+"%")
	}
	if query.Address != "" {
		db = db.Where("address LIKE ?", "%"+query.Address+"%")
	}
	if query.City != "" {
		db = db.Where("city = ?", query.City)
	}
	if query.Subject != "" {
		db = db.Where("subject = ?", query.Subject)
	}
	if query.Status != "" {
		db = db.Where("status = ?", query.Status)
	}
	if query.Pushed == 0 {
		db = db.Where("is_pushed = ?", false)
	} else if query.Pushed == 1 {
		db = db.Where("is_pushed = ?", true)
	}

	// 计算总数
	var total int64
	db.Count(&total)

	// 分页查询
	var customers []models.Customer
	offset := (query.Page - 1) * query.Size
	if err := db.Offset(offset).Limit(query.Size).Order("created_at DESC").Find(&customers).Error; err != nil {
		utils.InternalServerError(c, "查询客户失败")
		return
	}

	utils.PageSuccess(c, customers, total, query.Page, query.Size)
}

// GetCustomer 获取单个客户
func (cc *CustomerController) GetCustomer(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		utils.BadRequest(c, "客户ID无效")
		return
	}

	var customer models.Customer
	if err := cc.DB.Preload("Creator").Preload("PushRecords.Partner").First(&customer, uint(id)).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			utils.NotFound(c, "客户不存在")
		} else {
			utils.InternalServerError(c, "查询客户失败")
		}
		return
	}

	utils.Success(c, customer)
}

// CreateCustomer 创建客户
func (cc *CustomerController) CreateCustomer(c *gin.Context) {
	var req CustomerRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		utils.ValidationError(c, err)
		return
	}

	// 获取当前用户ID
	userID, exists := c.Get("user_id")
	if !exists {
		utils.Unauthorized(c, "用户未认证")
		return
	}

	// 检查手机号是否已存在
	var count int64
	cc.DB.Model(&models.Customer{}).Where("phone = ?", req.Phone).Count(&count)
	if count > 0 {
		utils.BadRequest(c, "手机号已存在")
		return
	}

	// 创建客户
	customer := models.Customer{
		Name:      req.Name,
		Phone:     req.Phone,
		Wechat:    req.Wechat,
		Address:   req.Address,
		Age:       req.Age,
		Gender:    req.Gender,
		City:      req.City,
		Subject:   req.Subject,
		Grade:     req.Grade,
		Notes:     req.Notes,
		Status:    req.Status,
		CreatedBy: userID.(uint),
	}

	if customer.Status == "" {
		customer.Status = "interested"
	}

	if err := cc.DB.Create(&customer).Error; err != nil {
		utils.InternalServerError(c, "创建客户失败")
		return
	}

	// 记录操作日志
	models.LogCustomerCreate(cc.DB, userID.(uint), customer.ID, "创建客户: "+customer.Name, c.ClientIP(), c.GetHeader("User-Agent"))

	utils.SuccessWithMessage(c, "创建客户成功", customer)
}

// UpdateCustomer 更新客户
func (cc *CustomerController) UpdateCustomer(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		utils.BadRequest(c, "客户ID无效")
		return
	}

	var req CustomerRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		utils.ValidationError(c, err)
		return
	}

	// 获取当前用户ID
	userID, exists := c.Get("user_id")
	if !exists {
		utils.Unauthorized(c, "用户未认证")
		return
	}

	// 查找客户
	var customer models.Customer
	if err := cc.DB.First(&customer, uint(id)).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			utils.NotFound(c, "客户不存在")
		} else {
			utils.InternalServerError(c, "查询客户失败")
		}
		return
	}

	// 检查手机号是否被其他客户使用
	if req.Phone != customer.Phone {
		var count int64
		cc.DB.Model(&models.Customer{}).Where("phone = ? AND id != ?", req.Phone, customer.ID).Count(&count)
		if count > 0 {
			utils.BadRequest(c, "手机号已被其他客户使用")
			return
		}
	}

	// 更新客户信息
	customer.Name = req.Name
	customer.Phone = req.Phone
	customer.Wechat = req.Wechat
	customer.Address = req.Address
	customer.Age = req.Age
	customer.Gender = req.Gender
	customer.City = req.City
	customer.Subject = req.Subject
	customer.Grade = req.Grade
	customer.Notes = req.Notes
	if req.Status != "" {
		customer.Status = req.Status
	}

	if err := cc.DB.Save(&customer).Error; err != nil {
		utils.InternalServerError(c, "更新客户失败")
		return
	}

	// 记录操作日志
	models.LogCustomerUpdate(cc.DB, userID.(uint), customer.ID, "更新客户: "+customer.Name, c.ClientIP(), c.GetHeader("User-Agent"))

	utils.SuccessWithMessage(c, "更新客户成功", customer)
}

// DeleteCustomer 删除客户
func (cc *CustomerController) DeleteCustomer(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		utils.BadRequest(c, "客户ID无效")
		return
	}

	// 获取当前用户ID
	userID, exists := c.Get("user_id")
	if !exists {
		utils.Unauthorized(c, "用户未认证")
		return
	}

	// 查找客户
	var customer models.Customer
	if err := cc.DB.First(&customer, uint(id)).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			utils.NotFound(c, "客户不存在")
		} else {
			utils.InternalServerError(c, "查询客户失败")
		}
		return
	}

	// 软删除客户
	if err := cc.DB.Delete(&customer).Error; err != nil {
		utils.InternalServerError(c, "删除客户失败")
		return
	}

	// 记录操作日志
	models.LogCustomerDelete(cc.DB, userID.(uint), customer.ID, "删除客户: "+customer.Name, c.ClientIP(), c.GetHeader("User-Agent"))

	utils.SuccessWithMessage(c, "删除客户成功", nil)
}

// UpdateCustomerStatus 更新客户状态
func (cc *CustomerController) UpdateCustomerStatus(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		utils.BadRequest(c, "客户ID无效")
		return
	}

	var req struct {
		Status string `json:"status" binding:"required,oneof=interested contacted signed_up"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		utils.ValidationError(c, err)
		return
	}

	// 获取当前用户ID
	userID, exists := c.Get("user_id")
	if !exists {
		utils.Unauthorized(c, "用户未认证")
		return
	}

	// 查找客户
	var customer models.Customer
	if err := cc.DB.First(&customer, uint(id)).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			utils.NotFound(c, "客户不存在")
		} else {
			utils.InternalServerError(c, "查询客户失败")
		}
		return
	}

	// 更新状态
	oldStatus := customer.Status
	if err := customer.UpdateStatus(cc.DB, req.Status); err != nil {
		utils.InternalServerError(c, "更新客户状态失败")
		return
	}

	// 记录操作日志
	details := "更新客户状态: " + customer.Name + " (" + oldStatus + " -> " + req.Status + ")"
	models.LogCustomerUpdate(cc.DB, userID.(uint), customer.ID, details, c.ClientIP(), c.GetHeader("User-Agent"))

	utils.SuccessWithMessage(c, "更新客户状态成功", customer)
}

// BatchUpdateStatus 批量更新客户状态
func (cc *CustomerController) BatchUpdateStatus(c *gin.Context) {
	var req struct {
		CustomerIDs []uint `json:"customer_ids" binding:"required"`
		Status      string `json:"status" binding:"required,oneof=interested contacted signed_up"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		utils.ValidationError(c, err)
		return
	}

	// 获取当前用户ID
	userID, exists := c.Get("user_id")
	if !exists {
		utils.Unauthorized(c, "用户未认证")
		return
	}

	// 批量更新状态
	for _, customerID := range req.CustomerIDs {
		var customer models.Customer
		if err := cc.DB.First(&customer, customerID).Error; err != nil {
			// 如果客户不存在，则跳过
			continue
		}
		oldStatus := customer.Status
		if err := customer.UpdateStatus(cc.DB, req.Status); err != nil {
			utils.InternalServerError(c, "更新客户状态失败")
			return
		}
		// 记录操作日志
		details := "更新客户状态: " + customer.Name + " (" + oldStatus + " -> " + req.Status + ")"
		models.LogCustomerUpdate(cc.DB, userID.(uint), customer.ID, details, c.ClientIP(), c.GetHeader("User-Agent"))
	}

	// 记录操作日志
	details := fmt.Sprintf("批量更新客户状态为: %s，影响 %d 个客户", req.Status, len(req.CustomerIDs))
	models.LogCustomerUpdate(cc.DB, userID.(uint), 0, details, c.ClientIP(), c.GetHeader("User-Agent"))

	utils.SuccessWithMessage(c, "批量更新状态成功", nil)
}

// BatchDelete 批量删除客户
func (cc *CustomerController) BatchDelete(c *gin.Context) {
	var req struct {
		CustomerIDs []uint `json:"customer_ids" binding:"required"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		utils.ValidationError(c, err)
		return
	}

	// 获取当前用户ID
	userID, exists := c.Get("user_id")
	if !exists {
		utils.Unauthorized(c, "用户未认证")
		return
	}

	// 批量软删除
	if err := cc.DB.Where("id IN ?", req.CustomerIDs).Delete(&models.Customer{}).Error; err != nil {
		utils.InternalServerError(c, "批量删除失败")
		return
	}

	// 记录操作日志
	details := fmt.Sprintf("批量删除客户，影响 %d 个客户", len(req.CustomerIDs))
	models.LogCustomerDelete(cc.DB, userID.(uint), 0, details, c.ClientIP(), c.GetHeader("User-Agent"))

	utils.SuccessWithMessage(c, "批量删除成功", nil)
}

// ImportCustomers 导入客户
func (cc *CustomerController) ImportCustomers(c *gin.Context) {
	// 获取当前用户ID
	userID, exists := c.Get("user_id")
	if !exists {
		utils.Unauthorized(c, "用户未认证")
		return
	}

	// 获取上传的文件
	file, err := c.FormFile("file")
	if err != nil {
		utils.BadRequest(c, "请选择要上传的文件")
		return
	}

	// 检查文件类型
	if !strings.HasSuffix(strings.ToLower(file.Filename), ".xlsx") && !strings.HasSuffix(strings.ToLower(file.Filename), ".xls") {
		utils.BadRequest(c, "只支持Excel文件格式")
		return
	}

	// 这里应该实现Excel文件解析和数据导入逻辑
	// 暂时返回成功响应
	count := 0 // 实际导入的记录数

	// 记录操作日志
	details := fmt.Sprintf("导入客户数据，共导入 %d 条记录", count)
	models.LogCustomerCreate(cc.DB, userID.(uint), 0, details, c.ClientIP(), c.GetHeader("User-Agent"))

	utils.SuccessWithMessage(c, "导入成功", gin.H{"count": count})
}

// GetCustomerStats 获取客户统计信息
func (cc *CustomerController) GetCustomerStats(c *gin.Context) {
	var stats struct {
		Total      int64 `json:"total"`
		Interested int64 `json:"interested"`
		SignedUp   int64 `json:"signed_up"`
		Enrolled   int64 `json:"enrolled"`
		Invalid    int64 `json:"invalid"`
	}

	// 获取总数
	cc.DB.Model(&models.Customer{}).Count(&stats.Total)

	// 按状态统计

	cc.DB.Model(&models.Customer{}).Where("status = ?", "interested").Count(&stats.Interested)
	cc.DB.Model(&models.Customer{}).Where("status = ?", "signed_up").Count(&stats.SignedUp)
	cc.DB.Model(&models.Customer{}).Where("status = ?", "enrolled").Count(&stats.Enrolled)
	cc.DB.Model(&models.Customer{}).Where("status = ?", "invalid").Count(&stats.Invalid)

	utils.Success(c, stats)
}

// GetCustomerFilters 获取客户过滤器选项
func (cc *CustomerController) GetCustomerFilters(c *gin.Context) {
	var cities []string
	var subjects []string

	// 获取所有城市
	cc.DB.Model(&models.Customer{}).Distinct("city").Where("city != ''").Pluck("city", &cities)

	// 获取所有科目
	cc.DB.Model(&models.Customer{}).Distinct("subject").Where("subject != ''").Pluck("subject", &subjects)

	filters := gin.H{
		"cities":   cities,
		"subjects": subjects,
	}
	utils.Success(c, filters)
}

// ExportCustomers 导出客户
func (cc *CustomerController) ExportCustomers(c *gin.Context) {
	// 获取查询参数
	search := c.Query("search")
	status := c.Query("status")
	city := c.Query("city")
	subject := c.Query("subject")

	// 构建查询
	query := cc.DB.Model(&models.Customer{})

	if search != "" {
		query = query.Where("name LIKE ? OR phone LIKE ? OR wechat LIKE ? OR address LIKE ?", "%"+search+"%", "%"+search+"%", "%"+search+"%", "%"+search+"%")
	}
	if status != "" {
		query = query.Where("status = ?", status)
	}
	if city != "" {
		query = query.Where("city = ?", city)
	}
	if subject != "" {
		query = query.Where("subject = ?", subject)
	}

	var customers []models.Customer
	if err := query.Find(&customers).Error; err != nil {
		utils.InternalServerError(c, "查询客户数据失败")
		return
	}

	// 这里应该实现Excel文件生成逻辑
	// 暂时返回JSON数据
	c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
	c.Header("Content-Disposition", "attachment; filename=customers.xlsx")

	// 实际应该生成Excel文件并返回
	utils.SuccessWithMessage(c, "导出功能开发中", customers)
}
